package com.blacksheep.mtm.service.Impl;

import com.blacksheep.mtm.dao.*;
import com.blacksheep.mtm.dto.front.OrderFrontDto;
import com.blacksheep.mtm.dto.report.*;
import com.blacksheep.mtm.pojo.common.DataTablesResult;
import com.blacksheep.mtm.pojo.manager.*;
import com.blacksheep.mtm.service.ReportService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.SimpleFormatter;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private TbOrderMapper orderMapper;
    @Autowired
    private TbOrderDeliveryMapper deliveryMapper;
    @Autowired
    private TbIceInMapper iceInMapper;
    @Autowired
    private TbIceOutMapper outMapper;
    @Autowired
    private TbBindOrderMapper bindOrderMapper;
    @Autowired
    private TbBoxDetailsMapper detailsMapper;
    @Autowired
    private TbBindBoxMapper bindBoxMapper;
    @Autowired
    private TbIceConfigMapper configMapper;
    @Autowired
    private TbDeviceMapper deviceMapper;
    @Override
    public OrderCount getOrderCount() {
        OrderCount orderCount = new OrderCount();
        orderCount.setTotal(orderMapper.selectCountByState(null));
        Integer[] state= {0};
        orderCount.setUncomfired(orderMapper.selectCountByState(state));
//        sstate {20};
        Arrays.fill(state,10);
        orderCount.setQuyao(orderMapper.selectCountByState(state));
        Arrays.fill(state,20);
        orderCount.setReview(orderMapper.selectCountByState(state));
        Arrays.fill(state,40);
        orderCount.setFinished(orderMapper.selectCountByState(state));
        state = new Integer[]{30,35};
        orderCount.setShip(orderMapper.selectCountByState(state));
        state = new Integer[]{-10};
        orderCount.setCancel(orderMapper.selectCountByState(state));
        return orderCount;
    }

    @Override
    public Integer getDeliveryPerformTotal() {
        return deliveryMapper.selectDeliveryPerforCount();
    }

    @Override
    public DataTablesResult getDeliveryPerformanceReport(int draw, int start, int length, String search, String minDate, String maxDate, String orderCol, String orderDir) {
        DataTablesResult result = new DataTablesResult();
        PageHelper.startPage(start / length + 1, length);
        List<DeliveryPerformance>  list = deliveryMapper.selectDeliveryPerfor("%" + search + "%",minDate,maxDate,orderCol, orderDir);
        PageInfo<DeliveryPerformance> pageInfo = new PageInfo<>(list);
        result.setRecordsFiltered((int)pageInfo.getTotal());
        result.setDraw(draw);
        result.setData(list);
        return result;
    }

    @Override
    public DataTablesResult getBoxUseRecords(int draw, int start, int length, String search, String minDate, String maxDate, String orderCol, String orderDir) {
        DataTablesResult result = new DataTablesResult();
        PageHelper.startPage(start / length + 1, length);
        List<BoxUseRecords>  list = bindOrderMapper.selectBoxUseRecords("%" + search + "%",minDate,maxDate,orderCol, orderDir);
        PageInfo<BoxUseRecords> pageInfo = new PageInfo<>(list);
        result.setRecordsFiltered((int)pageInfo.getTotal());
        result.setDraw(draw);
        result.setData(list);
        return result;

    }

    @Override
    public DataTablesResult getIceUseRecords(int draw, int start, int length, String search, String minDate, String maxDate, String orderCol, String orderDir) {
        DataTablesResult result = new DataTablesResult();
        PageHelper.startPage(start / length + 1, length+1);
        List<TbIceIn> iceInList  = iceInMapper.selectList("%" + search + "%",minDate,maxDate,"device_code,create_time","asc");
        List<IceUseRecords> resultList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        if (iceInList.size()>0){
            for (int i = 0; i < iceInList.size()-1; i++) {
                TbIceIn in = iceInList.get(i);
                Long min = in.getCreateTime();
                Long max = null;
                IceUseRecords iceUseRecords = new IceUseRecords();
                iceUseRecords.setIceCode(in.getDeviceCode());
                if (i<iceInList.size() && StringUtils.equals(iceInList.get(i+1).getDeviceCode() ,in.getDeviceCode())){
                    max = iceInList.get(i+1).getCreateTime();
                }
                TbIceOut out  = outMapper.selectMinOneByCode(in.getDeviceCode(),min,max);
                iceUseRecords.setInTime(new Date(in.getCreateTime()));
                if (out!=null){
                    iceUseRecords.setOutTime(new Date(out.getCreateTime()));
                    iceUseRecords.setFreezingTime((out.getCreateTime() - in.getCreateTime())/60/60/1000);
                    TbBoxDetails details = detailsMapper.selectOneByMinTimeAndCode(in.getDeviceCode(),sdf.format(new Date(out.getCreateTime())),max ==null?null:sdf.format(new Date(max)));
                    if (details!=null){
                        TbBindBox bindBox = bindBoxMapper.selectByPrimaryKey(details.getBindId());
                        if (bindBox !=null){
                            iceUseRecords.setBoxCode(bindBox.getBoxCode());
                        }
                        iceUseRecords.setBindTime(details.getCreateTime());
                        iceUseRecords.setUnFreezingTime((details.getCreateTime().getTime() - out.getCreateTime())/60/1000);
                    }
                }else{
                    iceUseRecords.setFreezingTime((new Date().getTime() - in.getCreateTime())/60/60/1000);
                }
                resultList.add(iceUseRecords);
            }
            resultList.remove(resultList.size()-1);
        }
        PageInfo<TbIceIn> pageInfo = new PageInfo<>(iceInList);
        result.setRecordsFiltered((int)pageInfo.getTotal());
        result.setDraw(draw);
        result.setData(resultList);
        return result;
    }




    @Override
    public DataTablesResult getIceStatusList(int draw, int start, int length, String search, String orderCol, String orderDir) {
        DataTablesResult result = new DataTablesResult();
        TbIceConfig iceConfig = configMapper.selectByPrimaryKey(1);
        HashMap<String,Integer> configMap = new HashMap<>();
        configMap.put("BBP",iceConfig.getBbpTime());
        configMap.put("LBP",iceConfig.getLbpTime());
        PageHelper.startPage(start / length + 1, length);

        List<IceNowStatusReocord>  list = deviceMapper.selectIceNowStatusReocords("%" + search + "%",orderCol, orderDir);
        for (IceNowStatusReocord r:list){
            if (r.getInTime() !=null && r.getOutTime() !=null){
                if (r.getInTime() > r.getOutTime()){
                    r.setFreezingTime(Math.round((new Date().getTime()-r.getInTime())/60/60/1000));
                    if ((new Date().getTime()-r.getInTime())/60/60/1000> configMap.get(r.getType())){
                        r.setState(1);
                    }else{
                        r.setState(0);
                    }
//                if (iceConfig.ge)
                }
                else if(r.getInTime() <= r.getOutTime()){
                    r.setState(2);
//                TbBindBox bindBox = bindBoxMapper.
                }
            }else if(r.getInTime() ==null&& r.getOutTime() !=null){
                r.setState(2);
                r.setFreezingTime(0);
            }else if (r.getOutTime() ==null && r.getInTime()!=null){
                r.setState(1);
            }
            r.setHandleType("冷冻");
        }
        PageInfo<IceNowStatusReocord> pageInfo = new PageInfo<>(list);
        result.setRecordsFiltered((int)pageInfo.getTotal());
        result.setDraw(draw);
        result.setData(list);
        return result;

    }

    @Override
    public DataTablesResult getOrderReport(int draw, int start, int length, String search, String minDate, String maxDate, String orderCol, String orderDir) {
        DataTablesResult result = new DataTablesResult();
        PageHelper.startPage(start / length + 1, length);
        List<OrderReport> list = orderMapper.selectOrderReport("%" + search + "%",minDate,maxDate,orderCol, orderDir);
        List<OrderReportCustomerCount> oldCustomerCounts = orderMapper.selectMemberCustomerCount(0,minDate,maxDate);
        List<OrderReportCustomerCount> newCustomerCounts = orderMapper.selectMemberCustomerCount(1,minDate,maxDate);
        HashMap<Long,Integer> oldCustomerCountsMap = new HashMap<>();
        HashMap<Long,Integer> newCustomerCountsMap = new HashMap<>();
        for (OrderReportCustomerCount c:oldCustomerCounts){
            int num = 1;
            if (oldCustomerCountsMap.containsKey(c.getMemberId())){
                num += oldCustomerCountsMap.get(c.getMemberId());
            }
            oldCustomerCountsMap.put(c.getMemberId(),num);
        }
        for (OrderReportCustomerCount c:newCustomerCounts){
            int num = 1;
            if (newCustomerCountsMap.containsKey(c.getMemberId())){
                num += newCustomerCountsMap.get(c.getMemberId());
            }
            newCustomerCountsMap.put(c.getMemberId(),num);
        }
        for (OrderReport o :list){
            int oldCustomer = 0;
            int newCustomer = 0;
            if (newCustomerCountsMap.containsKey(o.getMemberId())){
                newCustomer = newCustomerCountsMap.get(o.getMemberId());
            }
            if (oldCustomerCountsMap.containsKey(o.getMemberId())){
                oldCustomer = oldCustomerCountsMap.get(o.getMemberId());
            }
            o.setNewCustomerNums(newCustomer);
            o.setOldCustomerNUms(oldCustomer);
        }
        PageInfo<OrderReport> pageInfo = new PageInfo<>(list);
        result.setRecordsFiltered((int)pageInfo.getTotal());
        result.setDraw(draw);
        result.setData(list);
        return result;
    }
}
